import React, { useState, useRef, useEffect } from 'react';
import { Card, Button, Form, Col, Row, Select, message, Modal, Input, Checkbox } from 'antd';
import {
    BulbOutlined, AlignCenterOutlined, ExclamationCircleOutlined
} from '@ant-design/icons';
import { useSelector } from 'react-redux';

import {
    indlineledon, indlineledoff, indworkinglight, indworkingoff,
    indledopen, indledoff, indresetled, singleCalibrate, autoCalibrate,
    writeserial, positionList
} from "@/api/test";
import { getState } from '@/api/common';
import { COLOR_OPTIONS, LED_OPTIONS, SERIAL_OPTIONS, LED_TYPE_OPTIONS } from '@/utils/constants';
import { listToOptions, extractAllParams } from "@/utils";
import { useTranslation } from 'react-i18next';
import './index.scss';

// 提取常量
const INITIAL_INFO = {
    "ad_serial": "",
    "ipconfig": { "post": "", "ip": "", "cid": "" },
    "cid": "", "ip": "", "post": "", "msg": "",
    "serial_state": "", "state": "", "version": ""
};

const WORK_CHANNEL_OPTIONS = [
    { label: '1', value: '1' },
    { label: '2', value: '2' },
    { label: '3', value: '3' },
    { label: '4', value: '4' },
    { label: '5', value: '5' },
    { label: '6', value: '6' },
];

const CALIBRATE_OPTIONS = [
    { label: 'autotrain', value: 'autotrain' },
    { label: 'max', value: 'max' },
    { label: 'min', value: 'min' }
];

function Test(props) {
    const { t } = useTranslation();
    useEffect(() => {
        getLoad();
    }, []);
    const [info, setInfo] = useState(INITIAL_INFO);
    const [form] = Form.useForm();
    const [form2] = Form.useForm();
    const [form3] = Form.useForm();
    const [form4] = Form.useForm();
    const [form5] = Form.useForm();
    const [form6] = Form.useForm();
    const mcValue = Form.useWatch('mc', form6);
    const [ledType, setLedType] = useState([]);
    const [options4, setOptions4] = useState([]);
    const [messageList, setMessageList] = useState([]);
    const [mcList, setMcList] = useState([]);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [msg, setMsg] = useState('');
    const [modalContext, setModalContext] = useState(t('test.ensureNoMaterial'));
    const [modalType, setModalType] = useState(0);
    const MC_OPTIONS = [
        { label: t('test.setLightType'), value: "1" },
        { label: t('test.setStationNum'), value: "2" },
        { label: t('test.queryMCBoards'), value: "3" },
        { label: t('test.MCDebug'), value: "4" },
        { label: t('test.printSensorStatus'), value: "5" },
        { label: t('test.printLightStatus'), value: "6" },
        { label: t('test.clearTestRecords'), value: "7" },
        { label: t('test.enableTestMode'), value: "8" }
    ];
    // 提取重复的卡片标题渲染
    const renderCardTitle = (icon, titleKey) => (
        <div className='title'>
            {icon}
            <span className="tit">{t(titleKey)}</span>
        </div>
    );

    function setModal(type) {
        switch (type) {
            case 0:
                setModalType(type);
                setModalContext(t('test.ensureNoMaterial'));
                break;
            case 1:
                setModalType(type);
                setModalContext(t('test.operateWithCaution'));
                break;
            default:
                message.error(t('test.unknownError'));
                break;
        }
        setIsModalOpen(true);
    }

    function submit() {
        let type = modalType;
        switch (type) {
            case 0:
                singleCalibrate(form3.getFieldsValue()).then(res => {
                    cancel();
                    message.success(res.msg);
                });
                break;
            case 1:
                autoCalibrate(form4.getFieldsValue()).then(res => {
                    cancel();
                    message.success("auto calibrate：" + form4.getFieldsValue().calibrate + t('message.test.sent'));
                });
                break;
            default:
                message.error(t('test.unknownError'));
                break;
        }
    }

    function getLoad() {
        getState().then(res => {
            setInfo(res[0]);
        });
        positionList().then(res => {
            setOptions4(listToOptions(res));
        });
    }

    function onFinish(values) {
        let param = values;
        indlineledon(param).then(res => {
            setMsg(`${t('message.test.addr') + "：" + param.channel_num},${t('message.test.color') + "：" + param.channel_color},${t('message.test.startSend')}`);
        });
    }

    function onFinish2(values) {
        const param = {
            ...values,
            command: "worklight"
        };
        indworkinglight(param).then(res => {
            message.success(`${t('message.test.statusLight') + "：" + values.workchannel + t('message.test.startSend')}`);
        });
    }

    function onFinish3(values) {
        indledopen(values).then(res => {
            message.success(`${t('message.test.lightAddr') + "：" + values.light_led + t('message.test.star')}`);
        });
    }

    function onFinish4(values) {
        writeserial({ command: values.command }).then(res => {
            message.success(t('message.test.sent'));
            if (values.clear) {
                setMessageList([res.msg]);
            } else {
                setMessageList(prev => prev.concat(res.msg));
            }
        });
    }

    function close() {
        let param = {
            channel_num: form.getFieldsValue().channel_num,
            channel_color: 'off'
        };
        indlineledoff(param).then(res => {
            setMsg(`${t('message.test.light') + "：" + param.channel_num},${t('message.test.close')}`);
        });
    }

    function close2() {
        const param = {
            ...form2.getFieldsValue(),
            command: "workoff"
        };
        indworkingoff(param).then(res => {
            message.success(`${t('message.test.statusLight') + "：" + param.workchannel + t('message.test.closeSend')}`);
        });
    }

    function close3() {
        let param = {
            light_led: form3.getFieldsValue().light_led,
            light_led_color: 'off'
        };
        indledoff(param).then(res => {
            message.success(`${t('message.test.lightAddr') + "：" + param.light_led + t('message.test.close')}`);
        });
    }

    function reset() {
        indresetled().then(res => {
            message.success(t('message.test.light') + t('message.test.reset'));
        });
    }
    async function onFinish5(values) {
        writeserial({ command: await getMCparam(values) }).then(res => {
            message.success(t('message.test.sent'));
            if (values.clear) {
                setMcList([res.msg]);
            } else {
                setMcList(prev => prev.concat(res.msg));
            }
        });
    }
    function cancel() {
        setIsModalOpen(false);
    }
    function ledTypeChange(value) {
        if (ledType.length < 5) {
            let data = LED_TYPE_OPTIONS.filter(item => item.value == value);
            setLedType(prev => prev.concat(data));
        }
        form6.setFieldValue("ledType", "");
    }
    async function getMCparam(values) {
        let mc = values.mc;
        switch (mc) {
            case "1":

                let param = {
                    ADDR: values.addr,
                    ledtype: [...ledType.map(item => item.value), ...Array(5).fill('0')].slice(0, 5),
                };
                return JSON.stringify(param);
            case "2":
                let res = await writeserial({ command: JSON.stringify({ "ADDR": "1", "action": "info" }) });
                let data = extractAllParams(res.msg);
                let param2 = {
                    ADDR: "99",
                    addr: values.addr,
                    action: "siteid",
                    hwid: data.DeviceUniqueID
                };
                return JSON.stringify(param2);
            case "3":
                return JSON.stringify({ "ADDR": values.addr, "action": "report" });
            case "4":
                return JSON.stringify({ "ADDR": values.addr, "action": "diagnosMode" });
            case "5":
                return JSON.stringify({ "ADDR": values.addr, "action": "PrintStatus" });
            case "6":
                return JSON.stringify({ "ADDR": values.addr, "action": "LedBoardTest" });
            case "7":
                return JSON.stringify({ "ADDR": values.addr, "action": "ClearCheckList" });
            case "8":
                return JSON.stringify({ "ADDR": values.addr, "action": "factoryModeON" });
            default:
                break;
        }
    }
    return (
        <div className="test-container">
            <div className="row-a1">
                <div className="left">
                    {/* 灯带测试 */}
                    <div className="con-a1">
                        <Card title={renderCardTitle(<BulbOutlined style={{ color: '#08c' }} />, 'test.stripTest')}>
                            <Form
                                form={form}
                                initialValues={{ channel_num: '1', channel_color: 'red' }}
                                labelCol={{ span: 6 }}
                                onFinish={onFinish}
                            >
                                <Row>
                                    <Col span={12}>
                                        <Form.Item label={t('test.addressSelect')} name="channel_num">
                                            <Select options={LED_OPTIONS} getPopupContainer={triggerNode => triggerNode.parentElement} />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item label={t('test.colorSelect')} name="channel_color">
                                            <Select options={COLOR_OPTIONS} getPopupContainer={triggerNode => triggerNode.parentElement} />
                                        </Form.Item>
                                    </Col>
                                    <Col span={24}>
                                        <Form.Item>
                                            <Button className='submit-btn' type="primary" htmlType="submit">{t('test.open')}</Button>
                                            <Button className='close-btn' onClick={close} type="primary">{t('test.close')}</Button>
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Form>
                        </Card>
                    </div>

                    {/* 状态灯测试 */}
                    <div className="con-a1">
                        <Card title={renderCardTitle(<BulbOutlined style={{ color: '#08c' }} />, 'test.statusLightTest')}>
                            <Form
                                form={form2}
                                initialValues={{ workchannel: '1' }}
                                labelCol={{ span: 6 }}
                                onFinish={onFinish2}
                            >
                                <Row>
                                    <Col span={12}>
                                        <Form.Item label={t('test.selection')} name="workchannel">
                                            <Select options={WORK_CHANNEL_OPTIONS} getPopupContainer={triggerNode => triggerNode.parentElement} />
                                        </Form.Item>
                                    </Col>
                                    <Col span={24}>
                                        <Form.Item>
                                            <Button className='submit-btn' type="primary" htmlType="submit">{t('test.turnOn')}</Button>
                                            <Button className='close-btn' onClick={close2} type="primary">{t('test.turnOff')}</Button>
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Form>
                        </Card>
                    </div>

                    {/* 库位操作测试 */}
                    <div className="con-a1">
                        <Card title={renderCardTitle(<AlignCenterOutlined style={{ color: '#08c' }} />, 'test.locationOperationTest')}>
                            <Form
                                form={form3}
                                initialValues={{ light_led: 'NLMP-A1-001', light_led_color: 'red' }}
                                labelCol={{ span: 6 }}
                                onFinish={onFinish3}
                            >
                                <Row>
                                    <Col span={12}>
                                        <Form.Item label={t('test.location')} name="light_led">
                                            <Select options={options4} getPopupContainer={triggerNode => triggerNode.parentElement} />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item label={t('test.color')} name="light_led_color">
                                            <Select options={COLOR_OPTIONS} getPopupContainer={triggerNode => triggerNode.parentElement} />
                                        </Form.Item>
                                    </Col>
                                    <Form.Item>
                                        <Button className='submit-btn' type="primary" htmlType="submit">{t('test.turnOn')}</Button>
                                        <Button className='close-btn' onClick={close3} type="primary">{t('test.turnOff')}</Button>
                                        <Button className='close-btn' onClick={reset} type="primary">{t('test.reset')}</Button>
                                        <Button className='close-btn' onClick={() => setModal(0)} type="primary">{t('test.calibrate')}</Button>
                                    </Form.Item>
                                </Row>
                            </Form>
                        </Card>
                    </div>

                    {/* 校准 */}
                    <div className="con-a1">
                        <Card title={renderCardTitle(<AlignCenterOutlined style={{ color: '#08c' }} />, 'test.calibration')}>
                            <Form
                                form={form4}
                                initialValues={{ addr: '1', calibrate: 'autotrain' }}
                                labelCol={{ span: 6 }}
                                onFinish={() => setModal(1)}
                            >
                                <Row>
                                    <Col span={12}>
                                        <Form.Item label={t('test.addressNumber')} name="addr">
                                            <Select options={LED_OPTIONS} getPopupContainer={triggerNode => triggerNode.parentElement} />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item label={t('test.parameter')} name="calibrate">
                                            <Select options={CALIBRATE_OPTIONS} getPopupContainer={triggerNode => triggerNode.parentElement} />
                                        </Form.Item>
                                    </Col>
                                    <Form.Item>
                                        <Button className='submit-btn' type="primary" htmlType="submit">{t('test.autoCalibrate')}</Button>
                                    </Form.Item>
                                </Row>
                            </Form>
                        </Card>
                    </div>

                    {/* 串口调试 */}
                    <div className="con-a1">
                        <Card title={renderCardTitle(<AlignCenterOutlined style={{ color: '#08c' }} />, 'test.serialDebug')}>
                            <Form
                                form={form5}
                                initialValues={{ command: '', clear: false }}
                                labelCol={{ span: 6 }}
                                onFinish={onFinish4}
                            >
                                <Row>
                                    <Col span={12}>
                                        <Form.Item>
                                            <Select
                                                options={SERIAL_OPTIONS}
                                                onChange={(value) => form5.setFieldValue('command', value)}
                                                getPopupContainer={triggerNode => triggerNode.parentElement}
                                            />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item name="command"><Input /></Form.Item>
                                    </Col>
                                    <Col span={24}>
                                        <Form.Item name="clear" valuePropName="checked">
                                            <Checkbox>{t('test.autoClearHistory')}</Checkbox>
                                        </Form.Item>
                                    </Col>
                                    <Form.Item>
                                        <Button className='submit-btn' type="primary" htmlType="submit">{t('test.send')}</Button>
                                    </Form.Item>
                                </Row>
                            </Form>
                            <div className="message">
                                <div className="list">
                                    {messageList.map((item, index) => (
                                        <div className="li" key={index}><div className="txt">{item}</div></div>
                                    ))}
                                </div>
                            </div>
                        </Card>
                    </div>

                    {/* MC测试 */}
                    <div className="con-a1">
                        <Card title={renderCardTitle(<AlignCenterOutlined style={{ color: '#08c' }} />, 'test.mcConfig')}>
                            <Form
                                form={form6}
                                initialValues={{ mc: '1', addr: '1' }}
                                labelCol={{ span: 6 }}
                                onFinish={onFinish5}
                            >
                                <Row>
                                    <Col span={12}>
                                        <Form.Item label={t('test.func')} name="mc" rules={[{ required: true }]}>
                                            <Select options={MC_OPTIONS}  onChange={()=>{setLedType([])}} getPopupContainer={triggerNode => triggerNode.parentElement} />
                                        </Form.Item>
                                    </Col>
                                    <Col span={12}>
                                        <Form.Item label={t('message.test.addr')} name="addr" rules={[{ required: true }]}>
                                            <Select options={LED_OPTIONS} getPopupContainer={triggerNode => triggerNode.parentElement} />
                                        </Form.Item>
                                    </Col>
                                    {mcValue == '1' && (
                                        <>
                                            <Col span={12}>
                                                <Form.Item label={t('test.ledType')} name="ledType" extra={t('test.ledTypeMsg')}>
                                                    <Select
                                                        options={LED_TYPE_OPTIONS}
                                                        onChange={ledTypeChange}
                                                        getPopupContainer={triggerNode => triggerNode.parentElement}
                                                    />
                                                </Form.Item>
                                            </Col>
                                            <Col span={12}>
                                                <Form.Item label={t('test.param')} name="param">
                                                    <div>
                                                        {ledType.map((item, index) => (
                                                            <span key={index}>
                                                                {item.label}
                                                                {index < ledType.length - 1 && ","}
                                                            </span>
                                                        ))}
                                                    </div>
                                                </Form.Item>
                                            </Col>
                                        </>
                                    )}
                                    <Col span={24}>
                                        <Form.Item name="clear" valuePropName="checked">
                                            <Checkbox>{t('test.autoClearHistory')}</Checkbox>
                                        </Form.Item>
                                    </Col>
                                    <Col span={24}>
                                        <Form.Item>
                                            <Button className='submit-btn' type="primary" htmlType="submit">{t('test.send')}</Button>
                                            <Button className='close-btn' onClick={() => { setLedType([]) }} type="primary">{t('test.reset')}</Button>
                                        </Form.Item>
                                    </Col>
                                </Row>
                            </Form>
                            <div className="message">
                                <div className="list">
                                    {mcList.map((item, index) => (
                                        <div className="li" key={index}><div className="txt">{item}</div></div>
                                    ))}
                                </div>
                            </div>
                        </Card>
                    </div>

                </div>

                <div className="right">
                    {/* 测试信息 */}
                    <div className="con-a3">
                        <Card title={renderCardTitle(<ExclamationCircleOutlined style={{ color: '#08c' }} />, 'test.testInfo')}>
                            <div className="list">
                                <div className="li">
                                    <div className="tit">{t('common.runningStatus')}:</div>
                                    <div className="text">
                                        <div className={'light ' + info.state}></div>
                                        <div className={'txt ' + info.state}>
                                            {info.state === 'on' ? t('header.running') :
                                                info.state === 'off' ? t('header.stopped') : t('header.unknown')}
                                        </div>
                                    </div>
                                </div>
                                <div className="li">
                                    <div className="tit">{t('test.testMessage')}:</div>
                                    <div className="text"><div className="txt">{msg}</div></div>
                                </div>
                                <div className="li">
                                    <div className="tit">{t('test.serialStatus')}</div>
                                    <div className="text"><div className="txt">{info.serial_state}</div></div>
                                </div>
                            </div>
                        </Card>
                    </div>
                </div>
            </div>

            <Modal
                title={t('test.prompt')}
                cancelText={t('test.cancel')}
                okText={t('test.confirm')}
                open={isModalOpen}
                onOk={submit}
                onCancel={cancel}
            >
                <div>{modalContext}</div>
            </Modal>
        </div>
    );
}

export default Test;